// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.api.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
import org.xml.sax.SAXException;

/**
 * Provides ways to bould a XML Document object
 * @author web2me
 */
public class DocumentGenerator {
	
	/**
	 * Generates a XML Document from am existing file
	 * @param file A valid XML file
	 * @return the XML Document
	 * @throws Exception
	 */
	public static Document generate(InputStream stream) throws Exception{
		
		Document document = null;
		
		try{
			DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = builder.newDocumentBuilder();
			
			document = docBuilder.parse( stream );
		}catch(IOException e){
			throw new Exception(e);
		}catch(ParserConfigurationException e){
			throw new Exception(e);
		}catch(SAXException e){
			throw new Exception(e);
		}
		
		return document;
	}
	
	/**
	 * Generates a XML Document from a XML string
	 * @param fileContent A valid XML string
	 * @return the XML Document
	 * @throws Exception
	 */
	public static Document generate(String fileContent) throws Exception {
		
		Document document = null;
		Tidy tidy = new Tidy();
		tidy.setOnlyErrors(true);
		tidy.setShowWarnings(false);
		
		InputStream in = new ByteArrayInputStream(fileContent.getBytes()) ;
		OutputStream out = null;
		
		document = tidy.parseDOM(in, out);
		
		return document;
	}
}
